
import hmac
import json
import requests
import time
import sys

from coin.exchange.base.kr_rest.auth_base import AuthKey
from coin2.api_client.common import (SyncQueryer)


class FtxAuth(requests.auth.AuthBase):
  def __init__(self, key):
    self._key = AuthKey.from_file(key)

  def __call__(self, req: requests.PreparedRequest):
    # assert req.method == 'GET', req.method
    timestamp = int(time.time() * 1000)
    signature_payload = f'{timestamp}{req.method}{req.path_url}'.encode()

    if req.body:
      signature_payload += req.body

    signature = hmac.new(self._key.secret_key_bytes,
                         signature_payload, 'sha256').hexdigest()
    req.headers.update({
        'FTX-KEY': self._key.access_key,
        'FTX-TS': str(timestamp),
        'FTX-SIGN': signature,
    })

    req.headers.update({'FTX-SUBACCOUNT': self._key.owner})

    return req


class FtxPrivateClient():
  def __init__(self, key, mea, ip=None):
    self.key = key
    self.url = 'https://ftx.com'
    self.auth = FtxAuth(key)
    self.query = SyncQueryer(api_host=self.url, auth=self.auth, ip=ip)

  def get_open_order(self):
    method = "GET"
    path = "/api/orders"
    response = self.query.query(method=method, path=path)
    return response

if __name__ == "__main__":
  key_path = sys.argv[1]
  mea = sys.argv[2]
  config = {"key_path": key_path, "mea":mea}
  ftx = FtxPrivateClient(key_path, mea)
  resp = ftx.get_open_order()
  resp = resp.json()
  print(resp)